package com.guigu.service.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.entity.Users;
import com.guigu.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@SuppressWarnings("all")
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //TODO 1
//      	public User(String username,    用户名
//      	String password,                从数据库查出的密码
//      	Collection<? extends GrantedAuthority> authorities
//      	)
//      	{
//     		this(username, password, true, true, true, true, authorities);
//     }


    //todo 3 实现UserDetailsService 加 @Service

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.查询数据库判断用户是否存在，如果不存在就抛出 UsernameNotFoundException
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq(Users.USERNAME,username);
        Users user = usersMapper.selectOne(wrapper);
        System.out.println(user);
        if (user == null) {
            throw new  UsernameNotFoundException("用户名不存在!!!");
        }
        if (!username.equals("admin")) {
            throw new  UsernameNotFoundException("用户名不存在!!!");
        }


        //demo2 把查询出来的密码进行解析
        //demo2 这个相当于是数据库查询出来的加密后的密码
//        String encode = passwordEncoder.encode("123456");



        //admins emp ROLE_salary   ROLE_update,ROLE_up
        List<GrantedAuthority> auths = AuthorityUtils
                .commaSeparatedStringToAuthorityList("ROLE_update,ROLE_up,ROLE_salary,/main.html");

        return new User(user.getUsername(),
                        new BCryptPasswordEncoder().encode(user.getPassword()),
                        auths);
    }
}
